<?php

namespace app\api\controller\robat;

use app\api\controller\Base;

use app\api\controller\pub\Yhpcsoftasr;
use app\api\controller\pub\Siliconflow;
use app\api\controller\pub\Yunke as YunkePub;
use app\common\model\user\User;
use app\common\model\apiinput\Apiyunkeaccounts;
use app\common\model\apiinput\Apiyunkefriends;
use app\common\model\apiinput\Apiyunkerecords;
use app\common\model\user\Setting;
use app\common\model\customer\Customer;
use think\facade\Request;
use app\api\controller\Pub;

class Yunke extends Base
{
    /**
     * 云客api
     * getallRecords
        getcompanyAccounts
        getallFriends
     */


    public function initialize()
    {
        // parent::initialize();
        // $this->app_key = get_config_value('call_center_app_key');
        // $this->code = get_config_value('call_center_code');
    }

    /**
     * 将业务人员的微信信息取如到库里
     * @return [type] [description]
     */
    public function get_wechat_bussiness(){
        $yk = new YunkePub();
        $data = $yk->getcompanyAccounts();
        $ndata = [];
        $ayka = new Apiyunkeaccounts;
        foreach ($data['msg']['page'] as $key => $value) {
            $ndata[$key] = $value['data'][0];
            $ndata[$key]['userPhone'] = $value['userPhone'];
            //判断是否能找到此业务员的id
            $user = User::getinfo($ndata[$key]['userPhone']);
            if(!empty($user)){
                $ndata[$key]['BussinessId'] = $user['UserId'];
            }
            $sb = $ayka->get($ndata[$key]['wechatId']);
            if(empty($sb)){
                $ayka->save($ndata[$key]);
            }else{
                $ayka->saveAll([$ndata[$key]]);
            }
        }
        return myok('更新成功');
    }

    public function get_wechat_record_test(){
        dump(self::get_wechat_record());
    }

    /**
     * 将客户的微信信息更新到库里
     * cmd 执行语句 D:\phpstudy_pro\Extensions\php\php7.4.3nts\php.exe index.php /api/robat.yunke/get_wechat_customer
     * @return [type] [description]
     */
    public function get_wechat_customer(){
        $setdata = Setting::where('Title','api_yunke_get_wechat_customer_update')->find();
        $yk = new YunkePub();
        if(empty($setdata)){
            $data = $yk->getallFriends();
        }else{
            //默认更新截止时间为 这次的6天后 或者是当前这个时间
            $endtime = strtotime($setdata['Content'])+3600*24*6;
            //根据当前时间和最后的时间选择一个真实时间
            $endtime = $endtime>time()?time():$endtime;
            $endtime = date('Y-m-d H:i:s',$endtime);
            $data = $yk->getallFriends($setdata['Content'],$endtime);
        }
        $ndata = [];
        foreach ($data['msg'] as $key => $value) {
            $phone = '';//初始化phone
            $aykf = new Apiyunkefriends;
            $value['FId'] = $value['salesWechatId'].'_|_'.$value['id'];
            //判断是否能找到客户信息
            $sbay = $aykf->get($value['FId']);
            //找到客户，且客户已经绑定用户id 的话 直接跳过此客户
            if(!empty($sbay) && !empty($sbay['CustomerId'])){
                continue;
            }
            //更新客户手机号
            //判断是否存在手机号 phone 如果存在则用手机号去搜索客户信息表，搜到客户后绑定id
            if(!empty($value['phone'])){
                $phone = $value['phone'];
            }
            //如果没有手机号，则从微信id中把数字取出来尝试判断
            if(empty($phone) && !empty($value['alias'])){
                $ls = (int)filter_var($value['alias'], FILTER_SANITIZE_NUMBER_INT);
                if($ls>'10000000000'&&$ls<'20000000000'){
                    $phone = $ls;
                }
            }    
            //通过手机号寻找客户信息
            if(!empty($phone)){
                $customer = Customer::whereOr('Tel',$phone)->whereOr('UserTel',$phone)->whereOr('OtherTel','like','%'.$phone.'%')->value('CustomerId');
                if(!empty($customer)){
                    $value['CustomerId'] = $customer;
                }
            }
            //判断是否能找到此客户信息
            if(empty($sbay)){
                $aykf->save($value);
            }else{
                $aykf->saveAll([$value]);
            }
            echo "更新1条数据,这是第".$key."条，共".count($data['msg'])."条\n";
        }
        //更新设置表的状态
        if(empty($endtime)){
            //向此表插入数据
            $endtime = date('Y-m-d 00:00:00',time());
        }
        $setdata = new Setting;
        $setdata->saveData(['title'=>'api_yunke_get_wechat_customer_update','content'=>$endtime]);
        return myok('更新成功');
    }
    
    /**
     * 将客户的微信信息更新到库里
     * cmd 执行语句 D:\phpstudy_pro\Extensions\php\php7.4.3nts\php.exe index.php /api/robat.yunke/get_wechat_record
     * @return [type] [description]
     */
    public function get_wechat_record(){
        $setdata = Setting::where('Title','api_yunke_get_wechat_record_update')->find();
        $yk = new YunkePub();
        for ($i=0; $i < 100; $i++) {
            if(empty($setdata)){
                return serr('没有找到api_yunke_get_wechat_record_update配置数据');
            }else{
                //跳过晚上10点——8点这个时间段
                $h = (int)date('H',strtotime($setdata['Content']));
                if($h<=6||$h>=22){
                    if($h>=22){
                        $data['end'] = strtotime($setdata['Content'])+7500;
                    }else{
                        $data['end'] = strtotime($setdata['Content']);
                    }
                    $setdata = new Setting;
                    $setdata->saveData(['title'=>'api_yunke_get_wechat_record_update','content'=>date('Y-m-d 07:i:s',$data['end'])]);
                    return sok(date('Y-m-d H:i:s',$data['end'])."跳过非工作时间\n");
                }
                
                //获取下次执行获取的时间 毫秒所以*1000
                $time = (strtotime($setdata['Content']))*1000;
                //根据当前时间和最后的时间选择一个真实时间
                if($time>time()*1000){
                    return serr('无需获取新数据');
                }
                $data = $yk->getallRecords($time);
                if(!$data['code']){
                    return serr($data['msg']);
                }
                $data = $data['msg'];
            }
            if(empty($data['messages'])){
                $setdata = new Setting;
                $setdata->saveData(['title'=>'api_yunke_get_wechat_record_update','content'=>date('Y-m-d H:i:s',$data['end']/1000)]);
                return sok(date('Y-m-d H:i:s',$data['end']/1000)."的1小时内无数据\n");
            }else{
                break;
            }
        }
        $count = count($data['messages']);
        foreach ($data['messages'] as $key => $value) {
            $aykr = new Apiyunkerecords;
            //判断是否能找到客户信息
            $sbay = $aykr->get($value['msgSvrId']);
            //找到客户，且客户已经绑定用户id 的话 直接跳过此客户
            if(!empty($sbay)){
                continue;
            }
            //判断是否能找到此客户信息
            $aykr->save($value);
            echo "更新1条数据,这是第".$key."条，共".$count."条\n";
        }
        //更新设置表的状态
        if(empty($endtime)){
            //向此表插入数据
            $endtime = date('Y-m-d 00:00:00',time());
        }
        $setdata = new Setting;
        $setdata->saveData(['title'=>'api_yunke_get_wechat_record_update','content'=>date('Y-m-d H:i:s',$data['end']/1000)]);
        return sok('更新成功');
    }

    /**
     * 初始化微信聊天记录数据
     * cmd 执行语句 D:\phpstudy_pro\Extensions\php\php7.4.3nts\php.exe index.php /api/robat.yunke/init_wechat_record
     * @return [type] [description]
     */
    public function init_wechat_record(){
        set_time_limit(12000);
        for ($i=0; $i < 2400; $i++) { 
            $data = self::get_wechat_record();
            dump($data);
            //频繁调用接口会返回失败
            for ($ii=0; $ii < 5; $ii++) { 
                sleep(1);
                echo date('Y-m-d H:i:s',time())."请等待系统运行,第".$ii."秒\n";
            }
        }
        return myok('初始化结束');
    }
    
}